﻿using ETA.Web.App_Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ETA.IService;
using ETA.Entity;
using ETA.Dtos;
using ETA.ExtendEntity;
using ETA.Common;
using ETA.ClientService;

namespace ETA.Web.Controllers
{
    /// <summary>
    /// 网站后台管理
    /// </summary>
    [AuthFilter("网站后台管理员")]
    public class WebAdminController : BaseController
    {
        private static IQuestionService _IQuestionService { set; get; }
        private static IUserService _IUserService { set; get; }
        private static IJoinApplyFormService _IJoinApplyFormService { set; get; }
        private static IFlowStepService _IFlowStepService { set; get; }
        private static IWebMessageService _IWebMessageService { set; get; }

        public WebAdminController(IWebMessageService IWebMessageService,IUserService service, IQuestionService IQuestionService
            , IJoinApplyFormService IJoinApplyFormService, IFlowStepService IFlowStepService)
        {
            _IUserService = service;
            _IQuestionService = IQuestionService;
            _IJoinApplyFormService = IJoinApplyFormService;
            _IFlowStepService = IFlowStepService;
            _IWebMessageService = IWebMessageService;
        }


        /// <summary>
        /// 根据用户id返回用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ActionResult GetUserInfoById(string userId)
        {
            var user = UserBll.GetCompltetUserInfo(userId);
            var simpleUser = new { UserId = user.UserId, UserName = user.UserName, RolerId = user.Rolers.FirstOrDefault().RolerId, Note = user.Note };
            return JsonWithDate(simpleUser);
        }


        public ActionResult ModifyUser(string newUserName, string userId, string newRolerId, string note)
        {
            var user = UserBll.GetCompltetUserInfo(userId);
            var modifyUserResponse = new ModifyUserResponse();
            var queryRolerResponse = _IUserService.QueryRoler(new QueryRolerRequest());
            if (queryRolerResponse.Result.IsSuccess)
            {
                var rolerInfo = queryRolerResponse.Rolers.First(q => q.RolerId == newRolerId);
                user.Rolers.Clear();
                user.Rolers.Add(rolerInfo);
                user.UserName = newUserName.Trim();
                user.Note = note;
                modifyUserResponse = _IUserService.ModifyUser(new ModifyUserRequest { User = user });
            }
            return JsonWithDate(modifyUserResponse);
        }

        /// <summary>
        /// 帐号开关
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult UserStatus(string userIdStr, bool isDelete)
        {
            var res = new Response();
            res.Result.IsSuccess = true;
            var userArr = userIdStr.Split('$');
            if (userArr.Any())
            {
                foreach (var userId in userArr)
                {
                    var user = UserBll.GetCompltetUserInfo(userId);
                    var modifyUserResponse = new ModifyUserResponse();
                    user.IsDelete = isDelete;
                    modifyUserResponse = _IUserService.ModifyUser(new ModifyUserRequest { User = user });
                    if (!modifyUserResponse.Result.IsSuccess)
                    {
                        res.Result.IsSuccess = false;
                        res.Result.ErrMessage += "帐号：" + userId + "处理失败\n";
                    }
                }
            }
            return JsonWithDate(res);
        }

        public ActionResult AddUser(string userName, string rolerId, string note)
        {
            var response = new Response();
            UserDto userDto = new UserDto
            {
                UserName = userName,
                LoginName = userName,
                Note = note,
                Password = Config.DefaultPassword
            };
            var queryRolerResponse = _IUserService.QueryRoler(new QueryRolerRequest());
            if (queryRolerResponse.Result.IsSuccess)
            {
                var rolerInfo = queryRolerResponse.Rolers.First(q => q.RolerId == rolerId);
                userDto.Rolers = new List<Roler>() { rolerInfo };
                var createUserReq = new CreateUserRequest
                {
                    UserDto = userDto
                };
                var createUserResponse = _IUserService.AddUser(createUserReq, false);
                response.Result = createUserResponse.Result;
            }

            return Json(response);
        }

        //
        // GET: /WebAdmin/

        public ActionResult Index()
        {
            var rolerQueryRes = _IUserService.QueryRoler(new QueryRolerRequest());
            if (rolerQueryRes.Result.IsSuccess)
            {
                ViewBag.Rolers = rolerQueryRes.Rolers;
                ViewBag.FilterRolers = GetRolerDownList(rolerQueryRes.Rolers, "(全部)");
            }
            ViewBag.DefaultPassword = Config.DefaultPassword;
            var dropdownList = GetFlowStepDownList();
            ViewBag.flowStepList = dropdownList;
            ViewBag.FilePath = Config.FilePath;
            return View();
        }

        /// <summary>
        /// 获取页面步骤筛选下拉列表
        /// </summary>
        /// <returns></returns>
        private List<SelectListItem> GetFlowStepDownList()
        {
            var list = new List<SelectListItem>() { 
              new SelectListItem{
                 Text ="（全部）",
                 Value="-1",
                 Selected = true
              }
            };
            var rep = _IFlowStepService.QueryFlowStepList(new QueryFlowStepRequest());
            if (rep.Result.IsSuccess)
            {
                var flowSteps = rep.FlowSteps.OrderBy(s => s.FlowIndex);
                foreach (var step in flowSteps)
                {
                    list.Add(new SelectListItem
                    {
                        Text = step.FlowStepName,
                        Value = step.FlowStepId + ""
                    });
                }
            }
            if (list.Any())
            {
                var index = 1;
                list.ForEach(l =>
                {
                    if (l.Value != "-1")
                    {
                        l.Text = (index++) + "-" + l.Text;
                    }
                });
            }
            return list;
        }


        /// <summary>
        /// 返回角色下拉列表
        /// </summary>
        /// <param name="Rolers"></param>
        /// <param name="pref">前缀选项，比如说全部</param>
        /// <returns></returns>
        private List<SelectListItem> GetRolerDownList(IEnumerable<Roler> Rolers, string pref = "")
        {
            var list = new List<SelectListItem>();
            if (!string.IsNullOrEmpty(pref))
            {
                list.Add(new SelectListItem
                {
                    Text = pref,
                    Selected = true,
                    Value = "-1"
                });
            }
            if (Rolers.Any())
            {
                foreach (var r in Rolers)
                {
                    list.Add(new SelectListItem
                    {
                        Text = r.RolerName,
                        Value = r.RolerId
                    });
                }
            }
            return list;
        }


        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public ActionResult GetUsers(UserFilter filter)
        {
            var users = new List<UserView>();
            int rowCount = 0;
            users = _IUserService.GetFilterUser(out rowCount, filter);
            return Json(users);
        }

        /// <summary>
        /// 获取用户数量
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public ActionResult GetUsersCount(UserFilter filter)
        {
            int rowCount = 0;
            _IUserService.GetFilterUser(out rowCount, filter);
            return Json(rowCount);
        }


        public ActionResult GetQAList(QueryQuestionRequest req)
        {
            var list = new List<Question>();
            var count = 0;
            var response = _IQuestionService.QueryQuestionList(
           req, out count
            );
            if (response.Result.IsSuccess)
            {
                list = response.QuestionList.ToList();
            }
            return JsonWithDate(list);
        }


        public ActionResult AnswerQA(string qaId, string answerContent)
        {
            int count = 0;
            var res = _IQuestionService.QueryQuestionList(new QueryQuestionRequest
            {
                Question = new Entity.Question
                {
                    QuestionId = qaId
                }
            }, out count);

            var q = res.QuestionList.FirstOrDefault();
            q.AnswerTime = DateTime.Now;
            var currentUser = CurrentUser;
            q.AnswerUserId = currentUser.UserId;
            q.AnswerName = currentUser.UserName;
            q.AnswerContent = answerContent;
            var mRes = _IQuestionService.ModifyQuestion(new ModifyQuestionRequest
            {
                Question = q
            });

            //发送站内消息
            if (mRes.Result.IsSuccess && !string.IsNullOrEmpty(q.UserId) && !string.IsNullOrEmpty(answerContent.Trim()))
            {
                _IWebMessageService.CreateWebMessage(new CreateWebMessageRequest
                            {
                                WebMessage = new Entity.WebMessage
                                {
                                    WebMessageId = Guid.NewGuid() + "",
                                    Content = answerContent,
                                    MessageTypeEnum = DomainEnum.MessageTypeEnum.QA回复,
                                    UserId = q.UserId
                                }
                            });
            }
            return JsonWithDate(mRes);
        }
        public ActionResult GetQAById(string qaId)
        {
            Question qa = null;
            var count = 0;
            var response = _IQuestionService.QueryQuestionList(
            new QueryQuestionRequest
            {
                Question = new Question
                {
                    QuestionId = qaId
                }
            }, out count
            );
            if (response.Result.IsSuccess)
            {
                qa = response.QuestionList.FirstOrDefault();
            }
            return JsonWithDate(qa);
        }


        public ActionResult GetQACount(QueryQuestionRequest req)
        {
            var count = 0;
            var response = _IQuestionService.QueryQuestionList(
            req, out count
            );
            return JsonWithDate(count);
        }


        /// <summary>
        /// 加盟申请列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public ActionResult GetJoinLogs(QueryJoinApplyFormRequest req)
        {
            try
            {
                var list = new List<JoinApplyForm>();
                int count = 0;

                var res = _IJoinApplyFormService.QueryJoinApplyFormList(req, out count);
                if (res.Result.IsSuccess)
                {
                    list = res.JoinApplyForms.ToList();
                }
                return Json(list);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        ///加盟申请数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public ActionResult GetJoinsCount(QueryJoinApplyFormRequest req)
        {
            var count = 0;
            var res = _IJoinApplyFormService.QueryJoinApplyFormList(req, out count);
            return JsonWithDate(count);
        }

        /// <summary>
        /// 获取单条申请记录数据
        /// </summary>
        /// <param name="joinFormId"></param>
        /// <returns></returns>
        public ActionResult GetJoinFormById(string joinFormId)
        {
            return Json(GetJoinFormByIdSingle(joinFormId), JsonRequestBehavior.AllowGet);
        }

        public JoinApplyForm GetJoinFormByIdSingle(string joinFormId)
        {
            var count = 0;
            var res = _IJoinApplyFormService.QueryJoinApplyFormList(new QueryJoinApplyFormRequest
            {
                JoinFormId = joinFormId
            }, out count);
            if (res.Result.IsSuccess)
            {
                return res.JoinApplyForms.FirstOrDefault();
            }
            return null;
        }

        /// <summary>
        /// 成功加盟处理 1 更新状态 2 创建用户
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="rolerId"></param>
        /// <param name="note"></param>
        /// <param name="joinApplyId"></param>
        /// <returns></returns>
        public ActionResult SuccessJoin(string userName, string rolerId, string note, string joinApplyId)
        {
            var res = new Response();
            var applyForm = GetJoinFormByIdSingle(joinApplyId);

            if (applyForm != null && applyForm.HandlerStatus == 1)
            {
                res.Result.IsSuccess = false;
                res.Result.ErrMessage = "已成功加盟无须处理";
                return Json(res);
            }


            var response = new Response();
            UserDto userDto = new UserDto
            {
                UserName = userName,
                LoginName = userName,
                Note = note,
                Password = Config.DefaultPassword
            };
            var queryRolerResponse = _IUserService.QueryRoler(new QueryRolerRequest());
            if (queryRolerResponse.Result.IsSuccess)
            {
                var rolerInfo = queryRolerResponse.Rolers.First(q => q.RolerId == rolerId);
                userDto.Rolers = new List<Roler>() { rolerInfo };
                var createUserReq = new CreateUserRequest
                {
                    UserDto = userDto
                };
                var createUserResponse = _IUserService.AddUser(createUserReq, false);

                if (createUserResponse.Result.IsSuccess)
                {
                    //用户创建成功后  更新 申请状态
                    applyForm.User = createUserResponse.User;
                    applyForm.HandlerStatus = 1;
                    var modifyAppFormRes = _IJoinApplyFormService.ModifyJoinApplyForm(new ModifyJoinApplyFormRequest
                    {
                        JoinApplyForm = applyForm
                    });
                    response.Result = modifyAppFormRes.Result;
                }
                else
                {
                    response.Result = createUserResponse.Result;
                }
            }

            return Json(response);
        }

        public ActionResult BadApply(string joinApplyId,byte? handlerStatus)
        {
            var res = new Response();
            var applyForm = GetJoinFormByIdSingle(joinApplyId);

            if (applyForm != null && applyForm.HandlerStatus == 1)
            {
                res.Result.IsSuccess = false;
                res.Result.ErrMessage = "已成功加盟无须处理";
            }
            else
            {
                applyForm.HandlerStatus = handlerStatus;
                var modifyAppFormRes = _IJoinApplyFormService.ModifyJoinApplyForm(new ModifyJoinApplyFormRequest
                {
                    JoinApplyForm = applyForm
                });
                res.Result = modifyAppFormRes.Result;
            }

            return Json(res);
        }

    }
}
